package com.wuyu.acl.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuyu.acl.common.Result;
import com.wuyu.acl.dto.AdminPageQueryDto;
import com.wuyu.acl.po.Admin;
import com.wuyu.acl.po.AdminRole;
import com.wuyu.acl.service.AdminRoleService;
import com.wuyu.acl.service.AdminService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "用户管理")
@RestController
@RequestMapping("/admin/acl/user")
public class AdminController {

    @Resource
    private AdminService adminService;

    @Resource
    private AdminRoleService adminRoleService;

    /**
     * 用户管理：条件分页查询
     *
     * @param page
     * @param size
     * @param adminPageQueryDto
     * @return
     */
    @Operation(summary = "条件分页查询")
    @GetMapping("/{page}/{size}")
    public Result page(@PathVariable("page") Integer page,
                       @PathVariable("size") Integer size,
                       AdminPageQueryDto adminPageQueryDto) {
        String name = adminPageQueryDto.getName();
        Page<Admin> adminPage = adminService.page(new Page<>(page, size),
                new LambdaQueryWrapper<Admin>()
                        .like(StrUtil.isNotBlank(name), Admin::getUsername, name)
                        .or()
                        .like(StrUtil.isNotBlank(name), Admin::getNickname, name));
        return Result.ok(adminPage);
    }

    /**
     * 用户管理：添加用户
     *
     * @param admin
     * @return
     */
    @Operation(summary = "添加用户")
    @PostMapping
    public Result add(@RequestBody Admin admin) {
        adminService.save(admin);
        return Result.ok();
    }

    /**
     * 用户管理：删除用户
     *
     * @param ids
     * @return
     */
    @Operation(summary = "删除用户")
    @Transactional
    @DeleteMapping
    public Result remove(@RequestBody List<Long> ids) {
        adminService.removeBatchByIds(ids);
        adminRoleService.remove(
                new LambdaQueryWrapper<AdminRole>()
                        .in(AdminRole::getAdminId, ids));
        return Result.ok();
    }

    /**
     * 用户管理：修改用户
     *
     * @param admin
     * @return
     */
    @Operation(summary = "修改用户")
    @PutMapping
    public Result update(@RequestBody Admin admin) {
        adminService.updateById(admin);
        return Result.ok();
    }
}
